package com.breakfast.fun.ui.mall;

import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.base.BaseModel;
import com.breakfast.fun.base.BasePresenter;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.GoodCart;
import com.breakfast.fun.dao.GoodCartDao;
import com.breakfast.fun.data.entity.mall.Mall;
import com.breakfast.fun.event.GoodEvent;
import com.breakfast.fun.event.MallDetailEvent;
import com.breakfast.fun.ui.mall.cart.GoodCartActivity;
import com.breakfast.fun.ui.mall.comment.GoodCommentActivity;
import com.breakfast.fun.util.Api;
import com.breakfast.fun.view.widget.TitleBarView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import butterknife.Bind;

public class MallDetailActivity extends BaseActivity<BasePresenter, BaseModel> {


    @Bind(R.id.iv_mall_detail)
    ImageView mIvMallDetail;
    @Bind(R.id.tv_mall_detail_name)
    TextView mTvMallDetailName;
    @Bind(R.id.tv_mall_detail_price)
    TextView mTvMallDetailPrice;
    @Bind(R.id.tv_mall_detail_del)
    TextView mTvMallDetailDel;
    @Bind(R.id.tv_mall_detail_num)
    TextView mTvMallDetailNum;
    @Bind(R.id.tv_mall_detail_add)
    TextView mTvMallDetailAdd;
    @Bind(R.id.ll_mall_detail)
    LinearLayout mLlMallDetail;
    @Bind(R.id.iv_mall_detail_arrow)
    ImageView mIvMallDetailArrow;
    @Bind(R.id.rl_mall_detail)
    RelativeLayout mRlMallDetail;
    @Bind(R.id.wv_mall_detail)
    WebView mWvMallDetail;
    @Bind(R.id.rl_mall_comment)
    RelativeLayout mRlMallComment;
    @Bind(R.id.tbv_mall_detail)
    TitleBarView mTbvMallDetail;
    @Bind(R.id.tv_mall_detail_buy)
    TextView mTvMallDetailBuy;

    private Mall.DataBean.GoodsBean mGoodsBean;

    private Boolean isExpand = false;
    private GoodCartDao mGoodCartDao;
    private QueryBuilder qb;

    private GoodEvent event = new GoodEvent();
    private int totalNum = 0;
    private double totalPrice = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mall_detail;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);

        mGoodCartDao = DaoMaster.newDevSession(context, "zaofan.db").getGoodCartDao();

        totalNum = mGoodCartDao.loadAll().size();
        for (GoodCart goodCart : mGoodCartDao.loadAll()) {
            totalPrice += goodCart.getTotalPrice();
        }

        mGoodsBean = (Mall.DataBean.GoodsBean) getIntent().getSerializableExtra("goodsBean");
        if (getGoodList(mGoodsBean.getId()).size() != 0) {
            mTvMallDetailNum.setText(getGoodList(mGoodsBean.getId()).get(0).getCount() + "");
        }
        mTbvMallDetail.setBackListener(v -> {
            onBackPressed();
        });
        mTbvMallDetail.setTitleNoRight("商品详情");

        mTvMallDetailName.setText(mGoodsBean.getName());
        mTvMallDetailPrice.setText("￥" + String.format("%.2f", mGoodsBean.getPrice()));
        imageUtil.loadUrlImage(mGoodsBean.getImage(), mIvMallDetail);

        mRlMallComment.setOnClickListener(v -> {
            Intent intent = new Intent(context, GoodCommentActivity.class);
            intent.putExtra("productId", mGoodsBean.getId() + "");
            startActivity(intent);
        });

        if (TextUtils.isEmpty(mGoodsBean.getDes())) {
            mWvMallDetail.loadDataWithBaseURL(Api.BASE_URL, "暂无", "text/html", "UTF-8", null);
        } else {
            mWvMallDetail.loadDataWithBaseURL(Api.BASE_URL, Constant.html1 + mGoodsBean.getDes() + Constant.html2, "text/html", "UTF-8", null);
        }

        mRlMallDetail.setOnClickListener(v -> {
            if (!isExpand) {
                mWvMallDetail.setVisibility(View.VISIBLE);
                mIvMallDetailArrow.setImageResource(R.drawable.ic_arrow_up_gray);
            } else {
                mWvMallDetail.setVisibility(View.GONE);
                mIvMallDetailArrow.setImageResource(R.drawable.ic_arrow_down_gray);
            }
            isExpand = !isExpand;
        });

        mTvMallDetailAdd.setOnClickListener(v -> {
            List<GoodCart> goodCarts = getGoodList(mGoodsBean.getId());
            GoodCart goodCart = new GoodCart();
            if (goodCarts.size() == 0) {
                goodCart.setCount(1);
                goodCart.setImage(mGoodsBean.getImage());
                goodCart.setGoodId(mGoodsBean.getId());
                goodCart.setName(mGoodsBean.getName());
                goodCart.setPrice(mGoodsBean.getPrice());
                goodCart.setTotalPrice(mGoodsBean.getPrice());
                mGoodCartDao.insert(goodCart);
                mTvMallDetailNum.setText("1");
            } else {
                goodCarts.get(0).setCount(goodCarts.get(0).getCount() + 1);
                goodCarts.get(0).setTotalPrice(goodCarts.get(0).getPrice() * goodCarts.get(0).getCount());
                mGoodCartDao.update(goodCarts.get(0));
                mTvMallDetailNum.setText(goodCarts.get(0).getCount() + "");
            }
            totalNum += 1;
            totalPrice += mGoodsBean.getPrice();
            event.setTotalNum(totalNum);
            event.setTotalPrice(totalPrice);
            EventBus.getDefault().post(event);
        });

        mTvMallDetailDel.setOnClickListener(v -> {
            if (mTvMallDetailNum.getText().equals("0")) {
                return;
            }

            List<GoodCart> goodCarts = getGoodList(mGoodsBean.getId());
            goodCarts.get(0).setCount(goodCarts.get(0).getCount() - 1);
            mGoodCartDao.update(goodCarts.get(0));
            mTvMallDetailNum.setText(goodCarts.get(0).getCount() + "");
            if (mTvMallDetailNum.getText().equals("0")) {
                mGoodCartDao.delete(goodCarts.get(0));
            }
            totalNum -= 1;
            totalPrice -= mGoodsBean.getPrice();
            event.setTotalNum(totalNum);
            event.setTotalPrice(totalPrice);
            EventBus.getDefault().post(event);
        });

        mTvMallDetailBuy.setOnClickListener(v -> {
            Intent intent = new Intent(context, GoodCartActivity.class);
            intent.putExtra("isFromMall", true);
            startActivity(intent);
        });

    }

    public List<GoodCart> getGoodList(int goodId) {
        qb = mGoodCartDao.queryBuilder();
        Query query = qb.where(
                GoodCartDao.Properties.GoodId.eq(goodId))
                .build();
        return query.list();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MallDetailEvent event) {
        mTvMallDetailNum.setText(event.getCount() + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
